package cl.jpavlich.mpm.view.metawidgets;

import static org.metawidget.inspector.InspectionResultConstants.HIDDEN;
import static org.metawidget.inspector.InspectionResultConstants.NAME;
import static org.metawidget.inspector.InspectionResultConstants.READ_ONLY;
import static org.metawidget.inspector.InspectionResultConstants.TRUE;

import java.awt.Desktop;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.net.URI;
import java.util.Map;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTextField;

import org.metawidget.swing.SwingMetawidget;
import org.metawidget.util.ClassUtils;
import org.metawidget.widgetbuilder.iface.WidgetBuilder;

import cl.jpavlich.mpm.view.GUIUtils;

public class URLWidgetBuilder implements
WidgetBuilder<JComponent, SwingMetawidget> {

	public JComponent buildWidget(String elementName,
			Map<String, String> attributes, SwingMetawidget metawidget) {
		if (TRUE.equals(attributes.get(HIDDEN))) {
			return null;
		}

		if (attributes.get(NAME) == null) {
			return null;
		}

		Object obj = ClassUtils.getProperty(metawidget.getToInspect(), attributes.get(NAME));
		if (obj != null && obj instanceof URI) {
			final URI uri = (URI)obj;
			if (TRUE.equals(attributes.get(READ_ONLY))) {
				JLabel l = new JLabel("<html>URL: <a href=\""+uri.toString()+"\">"+uri.toString()+"</a></html>");
				
				
				l.addMouseListener(new MouseListener() {
					
					public void mouseReleased(MouseEvent e) {
						// TODO Auto-generated method stub
						
					}
					
					public void mousePressed(MouseEvent e) {
						// TODO Auto-generated method stub
						
					}
					
					public void mouseExited(MouseEvent e) {
						// TODO Auto-generated method stub
						
					}
					
					public void mouseEntered(MouseEvent e) {
						// TODO Auto-generated method stub
						
					}
					
					public void mouseClicked(MouseEvent e) {
						try {
							Desktop.getDesktop().browse(uri);
						} catch (IOException ex) {
							GUIUtils.showErrorDialog(ex);
						}
						
					}
				});
				return l;
			} else {
				return new JTextField(uri.toString());
			}
		} else {
			return null;
		}
	}

}
